<?php
namespace Service\Common;

/**
 * Desc: 代码克隆服务类
 * Created by PhpStorm.
 * User: xuanskyer | <furthestworld@icloud.com>
 * Date: 2016-7-20 14:40:30
 */


use Library\Util\Dir;

class CodeCloneService extends \Service\Service {


    CONST CODE_DNA = 'CodeDna';

    private $root_dir = __ROOT__;
    protected $userService;
    protected $db_map_obj = [
        'demo' => 'db',
    ];

    public function __construct() {
        parent::__construct();
        $this->initModels();
        $this->root_dir .= '/Stash/';
    }

    public function initModels() {
        $this->models->node   = new \Model\Node();
        $this->models->access = new \Model\Access();
        $this->models->userCacheKeys = new \Model\UserCacheKeys();
    }


    public function createModule($params = []) {

        $move_params = [

        ];
        $res         = $this->createModelFile($params['model'], $params);
        if (1 != $res['status']) {
            $this->clearStashDir();
            return $res;
        }
        array_push($move_params, $res['data']);
        $res = $this->createServiceFile($params['service'], $params);
        if (1 != $res['status']) {
            $this->clearStashDir();
            return $res;
        }
        array_push($move_params, $res['data']);
        $res = $this->createControllerFile($params['controller'], $params['module']);
        if (1 != $res['status']) {
            $this->clearStashDir();
            return $res;
        }
        $params['role']['controller_path'] = $res['data']['dest_file'];
        array_push($move_params, $res['data']);
        $res = $this->createViewFile($params['view'], $params['module']);
        if (1 != $res['status']) {
            $this->clearStashDir();
            return $res;
        }
        array_push($move_params, $res['data']);

        $res = $this->moveModule($move_params);
        if(1 != $res['status']){
            $this->clearStashDir();
            $false_file = implode('<br>', $res['data']);
            $res['info'] = $false_file . '<br>'. $res['info'];
            return $res;
        }
        $this->createAuthNodes($params);

        $this->clearUserCache();

        $res = $this->createRouteFile($params['router'], $params['module']);
        if (1 != $res['status']) {
            $this->clearStashDir();
            return $res;
        }
        $this->clearStashDir();
        return ['status' => 1, 'info' => '创建模块成功'];
    }

    protected function clearStashDir($dir_list = []){
        empty($dir_list) && $dir_list = [
            __ROOT__ . '/Stash/Model',
            __ROOT__ . '/Stash/Service',
            __ROOT__ . '/Stash/Controller',
            __ROOT__ . '/Stash/View',
            __ROOT__ . '/Stash/Conf',
        ];
        foreach((array)$dir_list as $dir){
            file_exists($dir) && Dir::DeleteDir($dir);
        }
    }
    /**
     * @node_name 清除用户缓存
     */
    protected function clearUserCache(){
        $this->userService = new UserService();
        $user_id = $this->userService->getLoginedUserId();
        if($user_id){
            $where = [
                'group_name' => $user_id
            ];
            $cache_key_list = $this->models->userCacheKeys->getListByWhere($where);
            if(!empty($cache_key_list)){
                $cache_keys = array_column($cache_key_list, 'cache_key');
                foreach($cache_keys as $val){
                    $res = $this->cache_memcached->delete($val);
                }
            }
        }
    }
    /**
     * @node_name 移动模块相关文件到指定位置
     * @param array $params
     * @return array
     */
    protected function moveModule($params = []) {
        $move_res = ['status' => 0, 'info' => '移动文件失败!', 'data' => []];
        foreach ($params as $val) {
            if (empty($val['old_dir']) || empty($val['new_dir'])) {
                if(file_exists($val['dest_file'])){
                    $move_res['data'][] = $val['dest_file'];
                }
            } elseif (is_array($val['source_file'])) {
                foreach ($val['source_file'] as $file) {
                    if(file_exists($val['new_dir'] . '/' . $file)){
                        $move_res['data'][] = $val['new_dir'] . '/' . $file;
                    }
                }
            }
        }
        if(!empty($move_res['data'])){
            $move_res['info'] = '模块相关同名文件已经存在！三思啊~';
            return $move_res;
        }
        foreach ($params as $val) {
            if (empty($val['old_dir']) || empty($val['new_dir'])) {
                $dir_name = dirname($val['dest_file']);
                if(!file_exists($dir_name)){
                    Dir::CreateDir($dir_name);
                }
                copy($val['source_file'], $val['dest_file']);
            } elseif (is_array($val['source_file'])) {
                if (!file_exists($val['new_dir'])) {
                    $res = Dir::CreateDir($val['new_dir']);
                }
                foreach ($val['source_file'] as $file) {
                    copy($val['old_dir'] . '/' . $file, $val['new_dir'] . '/' . $file);
                }
            }
        }
        return ['status' => 1, 'info' => '移动成功。。了吧。。'];
    }

    protected function clearStashDirs() {
        $clear_dirs = [
            'conf'       => __ROOT__ . '/Stash/Conf',
            'controller' => __ROOT__ . '/Stash/Controller',
            'service'    => __ROOT__ . '/Stash/Service',
            'model'      => __ROOT__ . '/Stash/Model',
            'view'       => __ROOT__ . '/Stash/View',
        ];
        foreach ($clear_dirs as $alias => $dir) {

        }
    }

    /**
     *  创建功能数据模型文件
     */
    protected function createModelFile($params = [], $params_all = []) {
//        $params    = [
//            'file_name'    => 'Model/TestAutoDev.php',
//            'replace_data' => [
//                'dna_namespace' => '',
//                'dna_class_name' => 'TestAutoDev',
//                'dna_table_name' => 'test_auto_dev',
//                'dna_db_name' => '',
//                  'dna_table_fields' => []
//            ]
//        ];
        if (!isset($params['replace_data']['dna_table_name']) || empty($params['replace_data']['dna_table_name'])) {
            $model_class_name = str_replace(['model', 'Model'], ['', ''], $params['replace_data']['dna_class_name']);
            $params['replace_data']['dna_table_name'] = preg_replace_callback('/[A-Z]/', function($matches){
                return '_'.strtolower($matches[0]);
            }, lcfirst($model_class_name));
        }
        $params['replace_data']['dna_db_name'] = $this->db_map_obj[$params['replace_data']['dna_db_name']];
        $params['replace_data']['dna_table_fields'] = var_export($this->formatFields($params['replace_data']['dna_table_fields']), true);
        $search    = [
            '{{{dna_namespace}}}',
            '{{{dna_class_name}}}',
            '{{{dna_db_name}}}',
            '{{{dna_table_name}}}',
            '{{{dna_table_fields}}}',
        ];
        $model_dna = file_get_contents(__ROOT__ . '/' . 'CodeDna/Model/ModelName.php.dna');
        if (!empty($model_dna)) {
            $model_dna_clone = str_replace($search, $params['replace_data'], $model_dna);
        }
        $new_file = $this->root_dir . $params['file_name'];
        $res      = Dir::CreateFile($new_file, 0755, true);
        if ($res['status']) {
            $res = file_put_contents($new_file, $model_dna_clone);
            if ($res) {
                return [
                    'status' => 1,
                    'info'   => '创建文件成功：' . $new_file,
                    'data'   => [
                        'source_file' => $new_file,
                        'dest_file'   => __ROOT__ . "/Model/{$params_all['module']['dna_module_dir']}/" . basename($params['file_name'])
                    ]
                ];
            }
        }
        return $res;
    }

    /**
     *  创建功能服务类文件
     * @param array $params_service
     * @param       $params_all
     * @return array|int
     */
    protected function createServiceFile($params_service = [], $params_all) {
//        $params_service    = [
//            'file_name'    => 'Service/TestAutoDevService.php',
//            'replace_data' => [
//                'dna_namespace'  => 'Service\Common',
//                'dna_class_name' => 'TestAutoDevService',
//                'dns_model_name' => 'TestAutoDevModel',
//                'dns_add_field_map' => []',
//                'dns_edit_field_map' => []',
//                'dns_list_field_map' => []',
//                'dna_model_use'  => '',
//            ]
//        ];
        $params_service['replace_data']['dns_add_field_map'] = var_export(
            $this->formatFormAddFields(
                $params_all['model']['replace_data']['dna_table_fields'],
                $params_all['model']['replace_data']['dna_table_fields_show'],
                $params_all['model']['replace_data']['dna_form_setting']
            ), true);
        $params_service['replace_data']['dns_edit_field_map'] = var_export(
            $this->formatFormEditFields(
                $params_all['model']['replace_data']['dna_table_fields'],
                $params_all['model']['replace_data']['dna_table_fields_show'],
                $params_all['model']['replace_data']['dna_form_setting']
            ), true);
        $params_service['replace_data']['dns_list_field_map'] = var_export(
            $this->formatFormListFields(
                $params_all['model']['replace_data']['dna_table_fields'],
                $params_all['model']['replace_data']['dna_table_fields_show'],
                $params_all['model']['replace_data']['dna_form_setting']
            ), true);

        $params_service['replace_data']['dna_model_use'] = 'Model' . '\\' .$params_all['module']['dna_module_dir']
            . '\\' . $params_all['model']['replace_data']['dna_class_name'];

        $search    = [
            '{{{dna_namespace}}}',
            '{{{dna_class_name}}}',
            '{{{dns_model_name}}}',
            '{{{dns_add_field_map}}}',
            '{{{dns_edit_field_map}}}',
            '{{{dns_list_field_map}}}',
            '{{{dna_model_use}}}',
        ];
        $model_dna = file_get_contents(__ROOT__ . '/' . 'CodeDna/Service/ServiceName.php.dna');
        if (!empty($model_dna)) {
            $model_dna_clone = str_replace($search, $params_service['replace_data'], $model_dna);
        }
        $new_file = $this->root_dir . $params_service['file_name'];
        $res      = Dir::CreateFile($new_file, 0755, true);
        if ($res['status']) {
            $res = file_put_contents($new_file, $model_dna_clone);
            if ($res) {
                return [
                    'status' => 1,
                    'info'   => '创建文件成功：' . $new_file,
                    'data'   => [
                        'source_file' => $new_file,
                        'dest_file'   => __ROOT__ . "/Service/{$params_all['module']['dna_module_dir']}/" . basename($params_service['file_name'])
                    ]
                ];
            }
        }
        return $res;
    }

    /**
     *  创建功能控制器文件
     */
    protected function createControllerFile($params = [], $module_params) {
//        $params    = [
//            'file_name'    => 'Controller/TestAutoDevController.php',
//            'replace_data' => [
//                'dna_doc_title'    => '自动化创建模块名称',
//                'dna_namespace'    => 'Controller\Common',
//                'dna_class_name'   => 'TestAutoDevController',
//                'dna_service_name' => 'TestAutoDevService',
//                'dna_use'          => 'Service\Common\TestAutoDevService',
//            ]
//        ];
        $search    = [
            '{{{dna_doc_title}}}',
            '{{{dna_namespace}}}',
            '{{{dna_class_name}}}',
            '{{{dna_service_name}}}',
            '{{{dna_use}}}',
        ];
        $model_dna = file_get_contents(__ROOT__ . '/' . 'CodeDna/Controller/ControllerName.php.dna');
        if (!empty($model_dna)) {
            $model_dna_clone = str_replace($search, $params['replace_data'], $model_dna);
        }
        $new_file = $this->root_dir . $params['file_name'];
        $res      = Dir::CreateFile($new_file, 0755, true);
        if ($res['status']) {
            $res = file_put_contents($new_file, $model_dna_clone);
            if ($res) {
                return [
                    'status' => 1,
                    'info'   => '创建文件成功：' . $new_file,
                    'data'   => [
                        'source_file' => $new_file,
                        'dest_file'   => __ROOT__ . "/Controller/Admin/{$module_params['dna_module_dir']}/" . basename($params['file_name'])
                    ]
                ];
            }
        }

        return $res;
    }

    /**
     *  创建功能模板文件
     */
    protected function createViewFile($params = [], $module_params) {
//        $params    = [
//            'dna_view_dir'    => 'View/TestAutoDev/TestAutoDev',
//            'copy_file' => [
//                'addData',
//                'editData',
//                'index'
//            ]
//        ];
        $view_dna_dir   = __ROOT__ . '/CodeDna/View';
        $view_clone_dir = $this->root_dir . $params['dna_view_dir'];
        $error_copy     = [];
        if (!file_exists($view_clone_dir)) {
            $res = Dir::CreateDir($view_clone_dir);
            if (!$res['status']) {
                return ['status' => 0, 'info' => '模板目录创建失败:' . $view_clone_dir];
            }
        }
        foreach ($params['copy_file'] as $file_name) {
            $source_file = "{$view_dna_dir}/{$file_name}.dna";
            $res         = copy($source_file, "{$view_clone_dir}/{$file_name}");
            if (!$res) {
                array_push($error_copy, $source_file);
            }
        }
        if (empty($error_copy)) {
            $ret = [
                'status' => 1,
                'info'   => '创建模板成功',
                'data'   => [
                    'old_dir'     => $view_clone_dir,
                    'new_dir'     => __ROOT__ . "/View/Admin/{$module_params['dna_module_dir']}/" . basename($params['dna_view_dir']),
                    'source_file' => $params['copy_file'],
                    'dest_file'   => ''
                ]
            ];
        } else {
            $ret = ['status' => 0, 'info' => '成功模板失败', 'data' => $error_copy];
        }
        return $ret;
    }


    /**
     *  创建功能路由文件
     */
    protected function createRouteFile($params = []) {
//        $params    = [
//            'route_file'    => 'Conf/router.conf',
//            'replace_data' => [
//                'route_desc' => '测试自动化生产的路由',
//                'dna_static' => 'develop/testautodev',
//                'dna_controller_path' => 'Develop\\TestAutoDev',
//            ]
//        ];
        $route_dna   = __ROOT__ . '/CodeDna/Conf/router.conf.dna';
        $route_clone = $this->root_dir . $params['route_file'];
        $res         = Dir::CreateFile($route_clone);
        if (!$res['status']) {
            return ['status' => 0, 'info' => '路由文件创建失败:' . $route_clone];
        }
        $search         = [
            '{{{route_desc}}}',
            '{{{dna_static}}}',
            '{{{dna_controller_path}}}',
        ];
        $route_dna_data = file_get_contents($route_dna);
        if (!empty($route_dna_data)) {
            $model_dna_clone = str_replace($search, $params['replace_data'], $route_dna_data);
            $res             = file_put_contents($route_clone, $model_dna_clone);
            if ($res) {
                file_put_contents(__ROOT__ . '/Conf/router.conf', $model_dna_clone, FILE_APPEND);
                return ['status' => 1, 'info' => '路由文件创建成功'];
            }
        }
        return ['status' => 0, 'info' => '路由文件创建失败' . $route_clone];
    }


    /**
     *  创建功能权限节点
     * @param array $params
     * @return array
     */
    protected function createAuthNodes($params = []) {
        if (isset($params['role']['role_id']) && is_array($params['role']['role_id']) && !empty($params['role']['role_id'])) {
            $where       = [
                'name'  => strtolower($params['module']['dna_module_dir']),
                'level' => 1
            ];
            $parent_node = $this->models->node->getOneByWhere($where);
            if (!empty($parent_node)) {
                $add_module_data = [
                    'name'    => $params['module']['dna_module_name'],
                    'title'   => empty($params['module']['dna_doc_title']) ? $params['module']['dna_module_name'] : $params['module']['dna_doc_title'],
                    'status'  => 1,
                    'pid'     => $parent_node['id'],
                    'level'   => 2,
                    'display' => 1
                ];
                $new_node_ids    = [];
                $res_add_id      = $this->models->node->add($add_module_data);
                if ($res_add_id) {
                    array_push($new_node_ids, ['node_id' => $res_add_id, 'level' => 2]);
                    $controller_name = "Controller\\Admin\\" . ucfirst($params['module']['dna_module_dir']) . '\\' . ucfirst($params['module']['dna_module_name']);
                    if (class_exists($controller_name)) {
                        $valid_functions = $this->getValidMethods($controller_name);
                        $reflector       = new \ReflectionClass($controller_name);
                        $parents         = array();
                        $class           = $reflector;
                        while ($parent = $class->getParentClass()) {
                            $parents[] = $parent->getName();
                            $class     = $parent;
                        }
                        foreach ($parents as $key => $val) {
                            $tmp = $this->getValidMethods($val, true);
                            !empty($tmp) && $valid_functions = array_merge($valid_functions, $tmp);
                        }
                        foreach ($valid_functions as $val) {
                            $add_data = [
                                'name'    => $val['name'],
                                'title'   => $val['title'],
                                'status'  => 1,
                                'pid'     => $res_add_id,
                                'level'   => 3,
                                'display' => 1
                            ];
                            $res      = $this->models->node->add($add_data);
                            array_push($new_node_ids, ['node_id' => $res, 'level' => 3]);
                        }
                        if (!empty($new_node_ids)) {
                            foreach ($params['role']['role_id'] as $role_id) {
                                foreach ($new_node_ids as $node) {
                                    $access_data = [
                                        'role_id' => $role_id,
                                        'node_id' => $node['node_id'],
                                        'level'   => $node['level'],
                                    ];
                                    $this->models->access->add($access_data);
                                }
                            }
                        }
                    }else{
                        return ['status' => 0, 'info' => '控制器类不存在' . $controller_name];
                    }
                }
            }
        }

    }

    /**
     * 获取符合权限节点显示条件的方法列表
     * @param string $class_name
     * @param bool   $check_comment
     * @return array
     */
    private function getValidMethods($class_name = '', $check_comment = false) {
        $valid_functions = array();
        if (class_exists($class_name)) {
            $reflector = new \ReflectionClass($class_name);
            $functions = $reflector->getMethods();
            foreach ((array)$functions as $key => $obj) {
                $show_function  = $check_comment ? $this->isValidCommentMethod($obj) : true;
                $obj_names[]    = $obj->name;
                $reflect_method = new \ReflectionMethod($class_name, $obj->name);
                if (($class_name == $obj->class) &&
                    ($reflect_method->isProtected() || $reflect_method->isPublic()) &&
                    !$reflect_method->isAbstract() &&
                    !$reflect_method->isConstructor() &&
                    $reflect_method->isUserDefined() && $show_function
                ) {
                    $comment = $obj->getDocComment();
                    if (!empty($comment) && preg_match('/@node_name[^\r\n\n]+/', $comment, $matches)) {
                        isset($matches[0]) && $node_name = str_replace(['@node_name', ' ', '\t'], '', $matches[0]);
                    } else {
                        $node_name = $obj->name;
                    }
                    $valid_functions[] = array(
                        'name'        => $obj->name,
                        'node_name'   => $obj->name,
                        'title'       => $node_name,
                        'node_title'  => $node_name,
                        'doc_comment' => $obj->getDocComment(),
                        'class_name'  => $class_name
                    );
                }

            }
        }
        return $valid_functions;
    }

    /**
     * 判定父类中的方法是否允许设置为子类的权限节点
     * @param string $function_obj
     * @return bool
     */
    private function isValidCommentMethod($function_obj = ''){
        $isShow = false;
        if(is_object($function_obj)){
            $has_doc_comment = strpos($function_obj->getDocComment(), '@show_in_subClass');
            (false !== $has_doc_comment) && ($isShow = true);
        }
        return $isShow;
    }

    private function formatFields($fields = []){
        $formatted_fields = [];
        foreach($fields as $field){
            $temp  =
                [
                    'name'  => $field['field'],
                    'type'  => $field['type'],
                    'form_type'  => $field['form_type'],
                    'title' => $field['comment'],
                    'extra' => $field['extra'],
                    'key' => $field['key'],
                    'null' => $field['null'],
                    'default' => $field['default']
                ];
            array_push($formatted_fields, $temp);
        }
        return $formatted_fields;
    }

    private function formatFormAddFields($fields = [], $fields_show = [], $field_setting = []){
        if(!empty($fields)){
            $formatted = [];
            foreach($fields as $field){
                $temp = [];
                if(isset($field['key']) && !empty($field['key'])){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => 'int',
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => true,
                        'form_config' => [
                            'name' => $field['field'],
                            'type' => isset($fields_show[$field['field']]['edit']) ? 'text' : 'hidden'
                        ],
                    ];
                }elseif('date' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => 'datetime',
                        'field_title' =>  empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['add']) ? true : false,
                        'form_config' => [
                            'name'   => $field['field'],
                            'title'  =>  empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'   => 'text',
                            'class'  => 'form-control lhgcalendar',
                            'output' => 'readonly',
                            'value' => empty($field['default']) ? date('Y-m-d H:i:s') : $field['default']
                        ],
                    ];
                }elseif('string' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['add']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'text',
                        ],
                    ];
                }elseif('text' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['add']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'textarea',
                        ],
                    ];
                }elseif('number' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['add']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'text',
                        ],
                    ];
                }elseif('select' == $field['form_type']){
                    $select_options = [];
                    if(isset($field_setting[$field['field']]) && !empty($field_setting[$field['field']])){
                        $explode_arr = explode(',', str_replace('，', ',',$field_setting[$field['field']]) );
                        foreach($explode_arr as $item){
                            $options_arr = explode('|', $item);
                            array_push($select_options, ['name' => $options_arr[1], 'value' => $options_arr[0]]);
                        }
                    }else{
                        $select_options = [
                            ['name' => '启用', 'value' => 1],
                            ['name' => '禁用', 'value' => 2],
                        ];
                    }
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['add']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'select',
                            'select_options' => $select_options,
                        ],
                    ];
                }
                !empty($temp) && array_push($formatted, $temp);
            }
            array_push($formatted, [
                'field_name'  => '',
                'field_type'  => '',
                'field_title' => '操作',
                'is_show'     => true,
            ]);
            return $formatted;
        }else{
            return [
                [
                    'field_name'  => 'id',
                    'field_type'  => 'int',
                    'field_title' => 'ID',
                    'is_show'     => true,
                    'form_config' => [
                        'name' => 'id',
                        'type' => 'hidden'
                    ],
                ],
                [
                    'field_name'  => 'name',
                    'field_type'  => 'varchar',
                    'field_title' => '名称',
                    'is_show'     => true,
                    'form_config' => [
                        'name'  => 'name',
                        'title' => '名称',
                        'type'  => 'text',
                    ],
                ],
                [
                    'field_name'  => 'description',
                    'field_type'  => 'text',
                    'field_title' => '描述',
                    'is_show'     => true,
                    'form_config' => [
                        'name'  => 'description',
                        'title' => '描述',
                        'type'  => 'textarea',
                    ],
                ],
                [
                    'field_name'  => 'created_time',
                    'field_type'  => 'datetime',
                    'field_title' => '新增时间',
                    'is_show'     => true,
                    'form_config' => [
                        'name'   => 'created_time',
                        'title'  => '新增时间',
                        'type'   => 'text',
                        'class'  => 'form-control lhgcalendar',
                        'output' => 'readonly',
                        'value' => date('Y-m-d H:i:s')
                    ],
                ],
                [
                    'field_name'  => 'updated_time',
                    'field_type'  => 'timestamp',
                    'field_title' => '更新时间',
                    'is_show'     => false,
                    'form_config' => [
                        'name'   => 'updated_time',
                        'title'  => '更新时间',
                        'type'   => 'text',
                        'class'  => 'form-control lhgcalendar',
                        'output' => 'readonly',
                    ],
                ],
                [
                    'field_name'  => 'status',
                    'field_type'  => 'tinyint',
                    'field_title' => '状态',
                    'is_show'     => true,
                    'form_config' => [
                        'name'           => 'status',
                        'title'          => '状态',
                        'type'           => 'select',
                        'select_options' => [
                            ['name' => '启用', 'value' => 1],
                            ['name' => '禁用', 'value' => 2],
                        ],
                    ],
                ],
                [
                    'field_name'  => 'sort',
                    'field_type'  => 'int',
                    'field_title' => '排序',
                    'form_config' =>
                        array (
                            'name' => 'sort',
                            'title' => '排序',
                            'type' => 'text',
                        ),
                ],
                [
                    'field_name'  => '',
                    'field_type'  => '',
                    'field_title' => '操作',
                    'is_show'     => true,
                ],
            ];
        }
    }

    private function formatFormEditFields($fields = [], $fields_show = [], $field_setting = []){
        if(!empty($fields)){
            $formatted = [];
            foreach($fields as $field){
                $temp = [];
                if(isset($field['key']) && !empty($field['key'])){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => 'int',
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => true,
                        'form_config' => [
                            'name' => $field['field'],
                            'type' => isset($fields_show[$field['field']]['edit']) ? 'text' : 'hidden'
                        ],
                    ];
                }elseif('date' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => 'datetime',
                        'field_title' =>  empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['edit']) ? true : false,
                        'form_config' => [
                            'name'   => $field['field'],
                            'title'  =>  empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'   => 'text',
                            'class'  => 'form-control lhgcalendar',
                            'output' => 'readonly',
                            'value' => empty($field['default']) ? date('Y-m-d H:i:s') : $field['default']
                        ],
                    ];
                }elseif('string' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['edit']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'text',
                        ],
                    ];
                }elseif('text' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['edit']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'textarea',
                        ],
                    ];
                }elseif('number' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['edit']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'text',
                        ],
                    ];
                }elseif('select' == $field['form_type']){
                    $select_options = [];
                    if(isset($field_setting[$field['field']]) && !empty($field_setting[$field['field']])){
                        $explode_arr = explode(',', str_replace('，', ',',$field_setting[$field['field']]) );
                        foreach($explode_arr as $item){
                            $options_arr = explode('|', $item);
                            array_push($select_options, ['name' => $options_arr[1], 'value' => $options_arr[0]]);
                        }
                    }else{
                        $select_options = [
                            ['name' => '启用', 'value' => 1],
                            ['name' => '禁用', 'value' => 2],
                        ];
                    }
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['edit']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'select',
                            'select_options' => $select_options,
                        ],
                    ];
                }
                !empty($temp) && array_push($formatted, $temp);
            }
            array_push($formatted, [
                'field_name'  => '',
                'field_type'  => '',
                'field_title' => '操作',
                'is_show'     => true,
            ]);
            return $formatted;
        }else{
            return [
                [
                    'field_name'  => 'id',
                    'field_type'  => 'int',
                    'field_title' => 'ID',
                    'is_show'     => true,
                    'form_config' => [
                        'name' => 'id',
                        'type' => 'hidden'
                    ],
                ],
                [
                    'field_name'  => 'name',
                    'field_type'  => 'varchar',
                    'field_title' => '名称',
                    'is_show'     => true,
                    'form_config' => [
                        'name'  => 'name',
                        'title' => '名称',
                        'type'  => 'text',
                    ],
                ],
                [
                    'field_name'  => 'description',
                    'field_type'  => 'text',
                    'field_title' => '描述',
                    'is_show'     => true,
                    'form_config' => [
                        'name'  => 'description',
                        'title' => '描述',
                        'type'  => 'textarea',
                    ],
                ],
                [
                    'field_name'  => 'created_time',
                    'field_type'  => 'datetime',
                    'field_title' => '新增时间',
                    'is_show'     => true,
                    'form_config' => [
                        'name'   => 'created_time',
                        'title'  => '新增时间',
                        'type'   => 'text',
                        'class'  => 'form-control lhgcalendar',
                        'output' => 'readonly',
                    ],
                ],
                [
                    'field_name'  => 'updated_time',
                    'field_type'  => 'timestamp',
                    'field_title' => '更新时间',
                    'is_show'     => false,
                    'form_config' => [
                        'name'   => 'updated_time',
                        'title'  => '更新时间',
                        'type'   => 'text',
                        'class'  => 'form-control lhgcalendar',
                        'output' => 'readonly',
                    ],
                ],
                [
                    'field_name'  => 'status',
                    'field_type'  => 'tinyint',
                    'field_title' => '状态',
                    'is_show'     => true,
                    'form_config' => [
                        'name'           => 'status',
                        'title'          => '状态',
                        'type'           => 'select',
                        'select_options' => [
                            ['name' => '启用', 'value' => 1],
                            ['name' => '禁用', 'value' => 2],
                        ],
                    ],
                ],
                [
                    'field_name'  => 'sort',
                    'field_type'  => 'int',
                    'field_title' => '排序',
                    'form_config' =>
                        array (
                            'name' => 'sort',
                            'title' => '排序',
                            'type' => 'text',
                        ),
                ],
                [
                    'field_name'  => '',
                    'field_type'  => '',
                    'field_title' => '操作',
                    'is_show'     => true,
                ],
            ];
        }
    }

    private function formatFormListFields($fields = [], $fields_show = [], $field_setting = []){
        if(!empty($fields)){
            $formatted = [];
            foreach($fields as $field){
                $temp = [];
                if(isset($field['key']) && !empty($field['key'])){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => 'int',
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['list']) ? true : false,
                        'is_search'   => isset($fields_show[$field['field']]['list']) ? true : false,
                        'form_config' => [
                            'name' => $field['field'],
                            'type' => 'hidden'
                        ],
                    ];
                }elseif('date' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => 'datetime',
                        'field_title' =>  empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['list']) ? true : false,
                        'is_search'   => isset($fields_show[$field['field']]['list']) ? true : false,
                        'form_config' => [
                            'name'   => $field['field'],
                            'title'  =>  empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'   => 'text',
                            'class'  => 'form-control lhgcalendar',
                            'output' => 'readonly',
                            'value' => empty($field['default']) ? date('Y-m-d H:i:s') : $field['default']
                        ],
                    ];
                }elseif('string' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['list']) ? true : false,
                        'is_search'   => isset($fields_show[$field['field']]['list']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'text',
                        ],
                    ];
                }elseif('text' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['list']) ? true : false,
                        'is_search'   => isset($fields_show[$field['field']]['list']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'textarea',
                        ],
                    ];
                }elseif('number' == $field['form_type']){
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['list']) ? true : false,
                        'is_search'   => isset($fields_show[$field['field']]['list']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'text',
                        ],
                    ];
                }elseif('select' == $field['form_type']){
                    $select_options = [];
                    if(isset($field_setting[$field['field']]) && !empty($field_setting[$field['field']])){
                        $explode_arr = explode(',', str_replace('，', ',',$field_setting[$field['field']]) );
                        foreach($explode_arr as $item){
                            $options_arr = explode('|', $item);
                            array_push($select_options, ['name' => $options_arr[1], 'value' => $options_arr[0]]);
                        }
                    }else{
                        $select_options = [
                            ['name' => '启用', 'value' => 1],
                            ['name' => '禁用', 'value' => 2],
                        ];
                    }
                    $temp = [
                        'field_name'  => $field['field'],
                        'field_type'  => $field['form_type'],
                        'field_title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                        'is_show'     => isset($fields_show[$field['field']]['list']) ? true : false,
                        'is_search'   => isset($fields_show[$field['field']]['list']) ? true : false,
                        'form_config' => [
                            'name'  => $field['field'],
                            'title' => empty($field['comment']) ? $field['field'] : $field['comment'],
                            'type'  => 'select',
                            'select_options' => $select_options,
                        ],
                    ];
                }
                !empty($temp) && array_push($formatted, $temp);
            }
            array_push($formatted, [
                'field_name'  => '',
                'field_type'  => '',
                'field_title' => '操作',
                'is_show'     => true,
            ]);
            return $formatted;
        }else{
            return [
                [
                    'field_name'  => 'id',
                    'field_type'  => 'int',
                    'field_title' => 'ID',
                    'is_show'     => true,
                    'is_search'   => true,
                    'form_config' => [
                        'name' => 'id',
                        'title' => 'ID',
                        'type' => 'text'
                    ],
                ],
                [
                    'field_name'  => 'name',
                    'field_type'  => 'varchar',
                    'field_title' => '名称',
                    'is_show'     => true,
                    'is_search'   => true,
                    'form_config' => [
                        'name'  => 'name',
                        'title' => '名称',
                        'type'  => 'text',
                        'data-control-action' => 'filter'
                    ],
                ],
                [
                    'field_name'  => 'description',
                    'field_type'  => 'text',
                    'field_title' => '描述',
                    'is_show'     => true,
                    'form_config' => [
                        'name'  => 'description',
                        'title' => '描述',
                        'type'  => 'textarea',
                    ],
                ],
                [
                    'field_name'  => 'created_time',
                    'field_type'  => 'datetime',
                    'field_title' => '新增时间',
                    'is_show'     => true,
                    'is_search'   => true,
                    'form_config' => [
                        'name'   => 'created_time',
                        'title'  => '新增时间',
                        'type'   => 'text',
                        'class'  => 'lhgcalendar',
                        'output' => 'readonly',
                        'data-control-action' => 'filterGeq'
                    ],
                ],
                [
                    'field_name'  => 'updated_time',
                    'field_type'  => 'timestamp',
                    'field_title' => '更新时间',
                    'is_show'     => true,
                    'is_search'   => true,
                    'form_config' => [
                        'name'   => 'updated_time',
                        'title'  => '更新时间',
                        'type'   => 'text',
                        'class'  => 'lhgcalendar',
                        'output' => 'readonly',
                        'data-control-action' => 'filterLeq'
                    ],
                ],
                [
                    'field_name'  => 'status',
                    'field_type'  => 'tinyint',
                    'field_title' => '状态',
                    'is_show'     => true,
                    'is_search'   => true,
                    'form_config' => [
                        'name'           => 'status',
                        'title'          => '状态',
                        'type'           => 'select',
                        'select_options' => [
                            ['name' => '启用', 'value' => 1],
                            ['name' => '禁用', 'value' => 2],
                        ],
                    ],
                ],
                [
                    'field_name'  => 'sort',
                    'field_type'  => 'int',
                    'field_title' => '排序',
                    'is_show'     => true,
                    'form_config' =>
                        array (
                            'name' => 'sort',
                            'title' => '排序',
                            'type' => 'text',
                        ),
                ],
                [
                    'field_name'  => '',
                    'field_type'  => '',
                    'field_title' => '操作',
                    'is_show'     => true,
                ],
            ];
        }
    }
}